
// miniprogram/pages/list/detial.js
const app = getApp();
const {getWeek} = require('../../util/helper');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    todoid: '',
    todoInfo: {},
    isonwer: false,
    isinvite: false,
    loading:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let { todoid } = options;
    if (!todoid) {
      wx.showToast({
        title: '参数错误',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    this.setData({ todoid });
    this.getTodoDetial();
  },
  getTodoDetial: function () {
    let page = this;
    const db = wx.cloud.database();
    db.collection('todos').doc(this.data.todoid).get().then(res => {
      page.setData({ todoInfo: res.data });
      page.getUser();
    })
  },
  getUser: function () {
    let page = this;
    let currentOpenId = app.globalData.openid;
    if (!currentOpenId) {
      wx.cloud.callFunction({
        name: 'login',
        complete: res => {
          currentOpenId = res.result.openid;
          page.checkUser(currentOpenId);
        }
      })
    } else {
      page.checkUser(currentOpenId);
    }
  },
  checkUser: function (currentUserOpenId) {
    let { openid, invite } = this.data.todoInfo;
    if (currentUserOpenId == openid) {
      this.setData({ isonwer: true,loading:false })
    } else {
      // 邀请用户打开
      if (invite && invite.length) {
        let user = invite.find(item => item.openid == currentUserOpenId);
        if (user) {
          this.setData({ isinvite: true ,loading:false})
        }
      }
    }
    this.setData({ loading:false})
  },
  openlocation: function () {
    let { longitude, latitude, address } = this.data.todoInfo;
    if (!longitude || !latitude) {
      return;
    }
    wx.openLocation({
      latitude,
      longitude,
      address
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let { nickName } = this.data.todoInfo
    return {
      title: `${nickName}邀请您参加约定`,
      path: `pages/list/detial?todoid=${this.data.todoid}`
    }
  },
  requestNotice: function (e) {
    let page = this;
    wx.requestSubscribeMessage({
      tmplIds: ['9fP7SL46Ny9kanVRYrPiJxhqvB4j8tl31Hlc3TTC_4A', 'ZX4URTu5Mi3j7Zy1w9jyZFvdFDOFJ7ZQXeQb6cx4YC4'],
      success(res) {
      },
      fail(res){
        console.log(res)
      }
    })
  },
  bindsbumit: function (e) {
    wx.showLoading({
      title: '接受中...',
    })
    let page =this;
    let userInfo = e.detail.userInfo;
    let { nickName, avatarUrl } = userInfo;
    wx.cloud.callFunction({
      name: 'accept',
      data:{
        todoid:this.data.todoid,
        nickName,
        avatarUrl,
      },
      complete: res => {
        wx.hideLoading()
        if(res && res.result){
          page.setData({isinvite:true});
          page.getTodoDetial();
        }
      }
    })
  }
})